<template>
  <el-dialog
    class="public-dialog"
    :title="`${isEdit ? '修改' : '新增'}`"
    width="70%"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div class="h-[660px]">
      <VForm
        ref="form"
        :model="model"
        :fieldList="fieldList"
        :options="formOption"
        :rules="rules"
        :disabled="disabled"
        :originOption="optionsData"
      >
        <template #far_fee-slot>
          <div
            class="text-[13px] text-[#9DA1AD] mt-[5px] w-[100%] leading-[24px]"
          >
            偏远费用系统逻辑为，检测到订单地址上，此国家（目地的），地址详情上有设置的地区名称(省市区地址详情1，地址详情2)或订单邮编吻合，则满足偏远费用，会把设置的偏远费用加到运费里面去
          </div>
        </template>
      </VForm>

      <FormTitle title="申报规则" />
      <RuleTable
        ref="tableRef"
        :optionsData="optionsData"
        :data="details"
        :id="model.id"
        @refresh="handleRefreshRule"
      />
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? '关闭' : '取消' }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from 'element-plus'
import VForm from '@/components/Form/index.vue'
import FormTitle from '@/components/Form/FormTitle.vue'
import RuleTable from './RuleTable/index.vue'

import {
  createDeclareRules,
  updateDeclareRules,
  declareRulesDetail,
} from '../api'

const props = defineProps({
  id: { type: [String, Number], default: '' },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
  optionsData: { type: Object, default: () => ({}) },
})

const emit = defineEmits(['update:modelValue', 'refresh', 'close'])

const formOption = {
  labelPosition: 'top',
  inline: true,
}

const rules = {
  rule_name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
  declare_type: [
    { required: true, message: '请输入规则名称', trigger: 'blur' },
  ],
}

const form = ref()
const model = ref({
  sku_specie: '1',
  sku: '1',
})
const loading = ref()
const tableRef = ref()
const details = ref()

const publicStyle = { style: { width: '300px' } }
const fieldList = [
  { label: '基础信息', type: 'title' },
  {
    field: 'rule_name',
    label: '规则名称',
    ...publicStyle,
  },
  {
    field: 'declare_type',
    label: '包裹包含多SKU时选择申报的产品信息',
    tooltip:
      '本项设置仅为确定申报所使用的品名及数量，对报关重量和价格无影响，类似备注功能',
    type: 'select',
    ...publicStyle,
    originField: 'declare_type',
  },
  {
    field: 'sku_specie',
    label: '申报的SKU品种数量',
    type: 'radio',
    options: {
      data: [
        { label: '全部申报', value: '1' },
        { label: '限制最多申报品种数', value: '2' },
      ],
    },
    ...publicStyle,
  },
  {
    field: 'sku_specie_total',
    label: '申报的SKU品种数量',
    type: 'number',
    ...publicStyle,
    show: ({ model }) => model.sku_specie === '2',
  },
  {
    field: 'sku',
    label: '申报的SKU总数量',
    type: 'radio',
    options: {
      data: [
        { label: '全部申报', value: '1' },
        { label: '限制最多申报品数量', value: '2' },
      ],
    },
    ...publicStyle,
  },
  {
    field: 'sku_total',
    label: '申报的SKU总数量',
    type: 'inputNumber',
    min: 1,
    ...publicStyle,
    show: ({ model }) => model.sku === '2',
  },
]

watch(
  () => props.id,
  val => {
    if (val) {
      nextTick(() => {
        getDetail(val)
      })
    }
  }
)

const getDetail = async (id, refreshRule) => {
  try {
    const { data } = await declareRulesDetail({ id })

    const {
      details: _details,
      sku_specie_total,
      sku_total,
      ...reset
    } = data || {}
    if (refreshRule) {
      details.value = _details
      return
    }
    model.value = {
      ...reset,
      sku_specie_total,
      sku_total,
      sku_specie: +sku_specie_total === 0 ? '1' : '2',
      sku: +sku_total === 0 ? '1' : '2',
    }
    details.value = _details
  } catch (e) {
    console.error(e)
  }
}

const handleRefreshRule = () => {
  getDetail(model.value.id, true)
}

const isEdit = computed(() => {
  return !!props.id
})

const handleSave = async () => {
  try {
    const formInfo = await form.value.submit()
    console.warn(formInfo)
    const api = {
      edit: updateDeclareRules,
      add: createDeclareRules,
    }
    const { id } = props

    const { sku_specie, sku_specie_total, sku, sku_total, ...reset } = formInfo
    const details = tableRef.value?.getTableData()
    if (!details.length) {
      ElMessage.warning('请添加申报规则')
      return
    }
    const { code, message } = await api[isEdit.value ? 'edit' : 'add']({
      id: id || undefined,
      ...reset,
      details,
      sku_specie_total: +sku_specie === 1 ? 0 : sku_specie_total,
      sku_total: +sku === 1 ? 0 : sku_total,
    })

    if (code !== 200) {
      ElMessage.warning(message)
      return
    }
    ElMessage.success(isEdit.value ? '修改成功' : '保存成功')
    handleClose(true)
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning('请检查表单信息')
    }
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleClose = async refresh => {
  model.value = {}
  await nextTick()
  form.value.resetForm()
  tableRef.value.remove()
  emit('update:modelValue', false)
  emit('close')
  if (refresh) emit('refresh')
}
</script>
